package com.sskj.gcc.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hey.lib.HeySpinner;
import com.sskj.common.util.CheckUtil;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.gcc.R;
import com.sskj.gcc.component.DaggerUserDataComponent;
import com.sskj.gcc.presenter.WithdrawActivityPresenter;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.common.rxbus2.RxBus;
import com.sskj.gocoin.common.widget.ToolBarLayout;
import com.sskj.gocoin.m.bean.ChargeCoinItemBean;
import com.sskj.gocoin.m.bean.CoinFeeBean;
import com.sskj.gocoin.v.activity.CapitalDetailsActivity;
import com.sskj.gocoin.v.activity.CashAddressListActivity;
import com.sskj.gocoin.v.base.BaseActivity;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

public class WithdrawActivity extends BaseActivity<WithdrawActivityPresenter> {

    @BindView(R.id.toolBar)
    ToolBarLayout toolBar;
    @BindView(R.id.tv_max_num)
    TextView tvMaxNum;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.iv_address)
    ImageView ivAddress;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.withdraw_unit)
    TextView withdrawUnit;
    @BindView(R.id.max_num_tv)
    TextView maxNumTv;
    @BindView(R.id.tvFee)
    TextView tvFee;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.bt_send_code)
    Button btSendCode;
    @BindView(R.id.et_check_code)
    EditText etCheckCode;
    @BindView(R.id.bt_withdraw)
    Button btWithdraw;
    @BindView(R.id.spinner)
    HeySpinner spinner;
    @BindView(R.id.activity_tab_layout)
    LinearLayout activityTabLayout;
    private String wallone;
    private String mTb_fee;
    private double minCoin = 0d;
    private double maxCoin = 0d;
    private DisposableSubscriber<Long> disposableSubscriber;
    private List<ChargeCoinItemBean> assetBeans;
    private String assetName;
    private int assetId;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_withdraw2;
    }

    @Override
    public WithdrawActivityPresenter getPresenter() {
        return new WithdrawActivityPresenter();
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, WithdrawActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        toolBar.setLeftButtonOnClickLinster(view -> finish());
        toolBar.setRightButtonOnClickLinster(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mActivity, CapitalDetailsActivity.class));
            }
        });
//        toolBar.setRightButtonOnClickLinster(view -> WithdrawRecordActivity.start(this));
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                if (userData != null) {
                }
            } else {
                userData = null;
            }
        });
        ClickUtil.click(btSendCode, () -> {
            if (CheckUtil.isEmail(MyAppLication.getMobile())) {
                mPresenter.sendEmail();
            } else {
                mPresenter.sendCode();
            }
        });
        ClickUtil.click(ivAddress, new ClickUtil.Click() {
            @Override
            public void click() {
                startActivityForResult(new Intent(WithdrawActivity.this, CashAddressListActivity.class).putExtra(Constants.INTENT_ASSET_ID, assetId).putExtra(Constants.INTENT_CALL_BACK, true), Constants.CASH_ADDRESS);
            }
        });

        ClickUtil.click(btWithdraw, new ClickUtil.Click() {
            @Override
            public void click() {
                if (TextUtils.isEmpty(etAddress.getText())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity205));
                    return;
                }
                if (TextUtils.isEmpty(etNumber.getText())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity206));
                    return;
                }
                Double aDouble = Double.valueOf(etNumber.getText().toString());
                if (aDouble < minCoin) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity207) + minCoin + App.INSTANCE.getString(R.string.strWithdrawActivity208));
                    return;
                }

//                if (aDouble > maxCoin) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity209) + maxCoin + App.INSTANCE.getString(R.string.strWithdrawActivity208));
//                    return;
//                }

                if (aDouble > Double.parseDouble(wallone)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity211));
                    return;
                }
                if (TextUtils.isEmpty(etPassword.getText())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strWithdrawActivity212));
                    return;
                }

                if (TextUtils.isEmpty(etCheckCode.getText())) {
                    ToastUtil.showShort(etCheckCode.getHint());
                    return;
                }

                if (userData.getConfig().getGoogle_verify() == 1) {
                    com.sskj.lib.util.TipUtil.googleCheckTip(WithdrawActivity.this, (pwd) -> {
                        mPresenter.requestGoogleCheck(pwd);
                    });
                } else {
                    //关闭之后不作处理
                    mPresenter.withdraw(etNumber.getText().toString().trim(),
                            etPassword.getText().toString().trim(),
                            etCheckCode.getText().toString().trim(),
                            etAddress.getText().toString().trim(), assetId, "");
                }

            }
        });

    }

    public void googleCheckSuccess(String googleCode) {
        mPresenter.withdraw(etNumber.getText().toString().trim(),
                etPassword.getText().toString().trim(),
                etCheckCode.getText().toString().trim(),
                etAddress.getText().toString().trim(), assetId, googleCode);
    }

    public void startCount() {
        btSendCode.setEnabled(false);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                btSendCode.setText(time + App.INSTANCE.getString(com.sskj.gocoin.R.string.strWithdrawActivity214));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                btSendCode.setText(App.INSTANCE.getString(com.sskj.gocoin.R.string.strWithdrawActivity215));
                btSendCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    /**
     * 提币结束
     */
    public void updateUI() {
        RxBus.getDefault().send(RxBusCode.TIBI_SUCCESS);
        if (disposableSubscriber != null) {
            disposableSubscriber.dispose();
        }
////        btSendCode.setEnabled(true);
////        etNumber.setText("");
////        etPassword.setText("");
////        etCheckCode.setText("");
//        getActivity().finish();
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK & requestCode == Constants.CASH_ADDRESS) {
            String address_url = data.getStringExtra("address_url");
            if (!TextUtils.isEmpty(address_url)) {
                etAddress.setText(address_url);
            }
        }
    }

    @Override
    protected void initData() {
        mPresenter.requestUserAssetList();
    }


    public void onDataSuccess(List<ChargeCoinItemBean> data) {
        Flowable.fromIterable(data)
                .filter(aseetBean -> !aseetBean.getCode().equals("GCT"))
                .toList()
                .subscribe(aseetBeans -> {
                    assetBeans = aseetBeans;
                    initSpinner();
                });
    }

    private void initSpinner() {
        List<String> data = new ArrayList<>();
        for (ChargeCoinItemBean bean : assetBeans) {
            data.add(bean.getCode());
        }
        spinner.attachData(data);
        spinner.setOnSelectListener(position -> {
            assetName = assetBeans.get(position).getCode();
            assetId = assetBeans.get(position).getId();
            wallone = assetBeans.get(position).getBalance();
            mTb_fee = assetBeans.get(position).getWithdraw_handling_fee();
            tvMaxNum.setText(App.INSTANCE.getString(R.string.strWithdrawActivity216) + assetBeans.get(position).getBalance() + assetName);
            minCoin = assetBeans.get(position).getWithdraw_min();
            maxCoin = assetBeans.get(position).getWithdraw_max();
            etNumber.setHint(App.INSTANCE.getString(R.string.strWithdrawActivity217) + assetBeans.get(position).getWithdraw_min());
            withdrawUnit.setText(assetName);
//        maxNumTv.setText(App.INSTANCE.getString(R.string.strBaseActivity227) + data.getTb_max());
            tvFee.setText(String.format(App.INSTANCE.getString(R.string.strWithdrawActivity219), mTb_fee));

        });
        spinner.setSelectIndex(0);
    }

}
